package form

import (
	"github.com/gin-gonic/gin"
	"path"
	"path/filepath"
	"strconv"
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

type ProfileForm struct {
	Nickname string `form:"Data[nickname]" validate:"max=36" chn:"昵称"`
	SendSms  int    `form:"Data[send_sms]"  validate:"gte=0,lte=1" chn:"短信通知"`
	Phone    string `form:"Data[phone]"  validate:"phone" chn:"手机号"`
	Avatar   string `form:"Data[avatar]"  validate:"max=128" chn:"头像"`
}

type PasswordForm struct {
	Password string `form:"password" validate:"max=36" chn:"密码"`
}

func (form *ProfileForm) Save(c *gin.Context) error  {
	if err := util.DefaultGetValidParams(c, form); err != nil {
		return err
	}
	admin := c.MustGet(util.AdminKey).(entity.Admin)
	db := util.GetMysqlPool().Handler()
	db.Model(&admin).Updates(map[string]interface{}{
		"nickname": form.Nickname, "send_sms": form.SendSms, "phone": form.Phone, "avatar": form.Avatar,
	})
	util.SaveSession(c, util.SessionAdminKey, admin)
	return nil
}

func (form *ProfileForm) UploadAvatar(c *gin.Context) (string, bool)  {
	admin := c.MustGet(util.AdminKey).(entity.Admin)
	folder := util.CreateDir("storage/avatar/admin")
	file, _ := c.FormFile("file")
	filename := filepath.Join(folder, strconv.Itoa(admin.Id)+path.Ext(file.Filename))
	if err := c.SaveUploadedFile(file, filename); err == nil {
		timeUnix := time.Now().Unix()
		return filepath.ToSlash(filename[8:]) + "?" + strconv.FormatInt(timeUnix, 10), true
	}
	return "头像保存失败!", false
}

func (form *PasswordForm) UpdatePassword(c *gin.Context) error {
	if err := util.DefaultGetValidParams(c, form); err != nil {
		return err
	}
	admin := c.MustGet(util.AdminKey).(entity.Admin)
	db := util.GetMysqlPool().Handler()
	db.Model(&admin).Update("password", admin.GetPassword(form.Password))
	util.SaveSession(c, util.SessionAdminKey, admin)
	return nil
}
